package com.zhansm.filesys.service.impl;

import com.zhansm.filesys.entity.FileEntity;
import com.zhansm.filesys.dao.FileDao;
import com.zhansm.filesys.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl  implements FileService {
    @Resource
    FileDao fileDao;

    @Value("${downloadAddr}")
    String downloadAddr;

    @Override
    public String uploadFile(byte[] bytes, String originalFilename) {
        String fileType = null;
        for (int i = originalFilename.length()-1;i>0;i--){
            if (originalFilename.charAt(i) == '.'){
                fileType = originalFilename.substring(i);
            }
        }
        String fileName = UUID.randomUUID().toString()+fileType;
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String format = dateFormat.format(date);
        //上传的文件默认存在e盘的fiel下
//        String fileAddr = "E:\\file\\"+format;
        String fileAddr = downloadAddr+format;
        try {
            File file = new File(fileAddr);
            if (!file.exists()){
               file.mkdirs();
            }
            fileAddr = fileAddr+"\\"+fileName;
            FileOutputStream fileOutputStream = new FileOutputStream(fileAddr);
            fileOutputStream.write(bytes);
            fileOutputStream.close();
        }catch (Exception e){
            return e.toString();
        }

        FileEntity fileEntity = new FileEntity();
        fileEntity.setFileAddr(fileAddr);
        fileEntity.setFileName(fileName);
        fileEntity.setFileSize(bytes.length);
        fileEntity.setOriginFileName(originalFilename);
        fileEntity.setUploadTime(date);
        fileDao.insert(fileEntity);
        return fileName;
    }

    @Override
    public void downloadFile(String fileName, HttpServletResponse response) throws Exception {
        //查库
        FileEntity fileEntity = fileDao.get(fileName);
        if (fileEntity == null){
            throw new Exception();
        }
        String fileAddr = fileEntity.getFileAddr();
        //写入数据
        InputStream inputStream = new FileInputStream(fileAddr);
        byte[] b = new byte[inputStream.available()];
        inputStream.read(b);
        export(fileEntity.getOriginFileName(),response,b);
    }

    @Override
    public FileEntity get(String fileName) {
        return fileDao.get(fileName);
    }

    private void export(String fileName, HttpServletResponse response,byte[] b) throws Exception {
//        response.setContentType("application;charset=utf-8");
        response.setContentType("application/octet-stream");    //下载用的流
        try {
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8),
                            "ISO8859-1"));
            response.setHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new Exception();
        }
        try (OutputStream outputStream = response.getOutputStream()) {
            outputStream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
